
const db = uniCloud.database();

// export const kAppKey = 'KWJjZGVmZzEyMzQ1Njc4OQ==';
export const kAppToken = {"$super":{"$super":{}},"words":[694313828,1701209905,842216501,909588537],"sigBytes":16};
export const kAppKey = "923412340977";
export function isNewUser(){
		const registerdate = uni.getStorageSync("registerdate")
		const currentTime = new Date().getTime();
		if((currentTime - registerdate) / 1000 < 24 * 60 * 60){
			return true;
		}
		return false;
}

export function compareTimestamp(timestamp) {
	const currentTime = new Date().getTime();
	const timeDiff = currentTime - timestamp;

	if (timeDiff < 60000) {
		return '1分钟内';
	} else if (timeDiff < 3600000) {
		return Math.floor(timeDiff / 60000) + '分钟';
	} else if (timeDiff < 86400000) {
		return Math.floor(timeDiff / 3600000) + '小时';
	} else if (timeDiff < 2592000000) {
		return Math.floor(timeDiff / 86400000) + '天';
	} else if (timeDiff < 7776000000) {
		return Math.floor(timeDiff / 2592000000) + '月';
	} else {
		return null;
	}
}

export function getTodayDateString(){
	const day = new Date();
	let today = ""+day.getFullYear() + (day.getMonth()+1) + day.getDate();
	return today;
}

export function getTodayMonthString(){
	const day = new Date();
	let today = ""+day.getFullYear() + (day.getMonth()+1);
	return today;
}


//提示框
export function showToast({
	title = "",
	duration = 1500,
	icon = "none",
	mask = false
} = {}) {
	uni.showToast({
		title: String(title),
		icon,
		duration,
		mask
	})
}

export function gotoHome() {
	uni.showModal({
		title: "提示",
		content: "页面有误将返回首页",
		showCancel: false,
		success: (res) => {
			if (res.confirm) {
				uni.reLaunch({
					url: "/pages/index/index"
				})
			}
		}
	})
}


const startScore = 2000;

export function getUserScore() {
	try {
		const value = uni.getStorageSync('myScore');
		if (value && value >= 0) {
			return value;
		} else {
			uni.setStorageSync('myScore', '' + startScore);
			return startScore;
		}
	} catch (e) {
		// error
		return startScore;
	}
}

export function addUserScore(score) {
	try {
		let value = uni.getStorageSync('myScore');
		let sum = Number(value) + score;
		if (sum < 0) {
			// uni.setStorageSync('myScore', 0);
			uni.showToast({
				title: '积分不够了',
				icon: "none",
				duration: 1500
			})
			return -1;
		} else {
			uni.setStorageSync('myScore', '' + sum);
			return sum;
		}
	} catch (e) {
		// error
		uni.showToast({
			title: '数据异常，请稍后再试',
			icon: "none",
			duration: 1500
		})
		return -1;
	}
}


export function getUserOpenId() {
	return new Promise((resolve, reject) => {
		const openid = uni.getStorageSync("UserOpenId");
		if (openid !== undefined && openid !== "") {
			resolve(openid);
		} else {
			uni.login({
				provider: "weixin",
				success: (res) => {
					if (res !== undefined && res.code) {
						uniCloud.callFunction({
							name: "getOpenId",
							data: {
								code: res.code
							}
						}).then(res => {
							if (res !== undefined && res.result !== undefined) {
								uni.setStorage({
									data: res.result,
									key: "UserOpenId",
									success: () => {},
								});
								resolve(res.result);
							}
						})
					}
				},
				fail(e) {
					reject(e);
				}
			});
		}
	});
}


export async function getUserScoreCloud() {
	try {
		const openid = await getUserOpenId();
		const userInfo = await db.collection("uni-id-users").where({
			username: openid.toLowerCase()
		}).field('score as score').get();
		return userInfo.result.data[0].score;
	} catch (e) {
		console.log("getUserScoreCloud error:" + e);
		return -1;
	}
}

export async function addUserScoreCloud(score) {
	try {
		const openid = await getUserOpenId();
		let userScore = await getUserScoreCloud();
		if (userScore == -1) {
			uni.showToast({
				title: '数据异常，请稍后再试',
				icon: "none",
				duration: 1500
			})
			return -1;
		}
		let sum = userScore + score;
		if (sum < 0) {
			uni.showToast({
				title: '积分不够了',
				icon: "none",
				duration: 1500
			})
			return -1;
		} else {
			await db.collection("uni-id-users").where({
				username: openid.toLowerCase()
			}).update({
				score: dbCmd.inc(score)
			});
			return sum;
		}
	} catch (e) {
		// error
		uni.showToast({
			title: '数据异常，请稍后再试',
			icon: "none",
			duration: 1500
		})
		return -1;
	}
}



export function SignInGetScore() {
	let today = new Date().getFullYear() + new Date().getMonth() + new Date().getDay()
	try {
		const value = uni.getStorageSync('SignIn');
		if (value === today) {
			uni.showToast({
				title: '已签到，明天再来试试吧',
				icon: "none",
				duration: 1500
			})
			return getUserScore();
		} else {
			uni.showToast({
				title: '签到成功',
				icon: "success",
				duration: 1500
			})
			uni.setStorageSync('SignIn', today)
			const value = uni.getStorageSync('myScore');
			if (value && value > 0) {
				uni.setStorageSync('myScore', '' + value + startScore)
			} else {
				uni.setStorageSync('myScore', '' + startScore);
			}
		}
		return getUserScore();
	} catch (e) {
		// error
		return getUserScore();
	}
}